package com.hezuti.common.url.dispatch;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

import org.apache.log4j.Logger;

public class CommonDispatcher implements BaseDispatcher {
	protected int totalWeight = 0;
	protected List<int[]> weightArray;
	protected List<BaseDispatchObject> objectList;
	protected Random random;
	private static final Logger logger;
	
	static {
		logger = Logger.getLogger(CommonDispatcher.class);
	}
	
	private CommonDispatcher() {
		
	}
	
	public CommonDispatcher(List list) {
		random = new Random();
		setDispatchObjects(list);
	}

	@Override
	public BaseDispatchObject getObject() {
		if(totalWeight > 0) {
			int target = random.nextInt(totalWeight);
			int low = 0;
			int high = objectList.size()-1;
			int mid;
			
			while(low <= high) {
				mid = (low+high)/2;
				int[] weight = (int[]) weightArray.get(mid);
				if(target >= weight[0] && target < weight[1]) {
					return objectList.get(mid);
				} else if(target < weight[0]) {
					high = mid-1;
				} else {
					low = mid+1;
				}
			}
		}
		
		if(objectList.size() > 0) {
			return objectList.get(random.nextInt(objectList.size()));
		}
		
		return null;
	}
	
	protected void calculateWeight(List<BaseDispatchObject> list) {
		if(list != null) {
			weightArray = new ArrayList<int[]>();
			int last = 0;
			int total = 0;
			for(int i = 0; i < list.size(); i++) {
				int weight = ((BaseDispatchObject) list.get(i)).getWeight();
				total += weight;
				int[] weights = new int[2];
				weights[0] = last;
				weights[1] = total;
				weightArray.add(weights);
				logger.info("host weight: "+weight);
				last = total;
			}
			totalWeight = total;
			logger.info("total weight: "+totalWeight);
		}
	}

	public void setDispatchObjects(List<BaseDispatchObject> list) {
		objectList = list;
		calculateWeight(objectList);
	}
}